package com.sunday.aomicaichang.ui.product;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.AssessAdapter;
import com.sunday.aomicaichang.event.UpdateProductList;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.Assess;
import com.sunday.member.base.BaseFragment;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/7.
 */

public class ProductAssessFragment extends BaseFragment {
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private AssessAdapter adapter;
    private List<Assess> dataSet = new ArrayList<>();

    private LinearLayoutManager layoutManager;
    private int lastVisibleItem;
    private boolean isCanloadMore;
    private int pagNo = 1;
    private int pageSize = 10;
    private long id;
    public static ProductAssessFragment newInstance(long id) {
        ProductAssessFragment fragment = new ProductAssessFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id", id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_product_assess, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void onEvent(UpdateProductList updateProductList){
        pagNo=1;
        getData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            id =getArguments().getLong("id");
        }
        EventBus.getDefault().register(this);
        initRecylerView();
        getData();
    }


    private void initRecylerView() {
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        layoutManager = new LinearLayoutManager(getActivity());
        adapter=new AssessAdapter(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter.setmData(dataSet);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pagNo=1;
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pagNo = 1;
                getData();
            }
        });
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{ "type","outClassId", "pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{ "1",  String.valueOf(id),String.valueOf(pageSize),
                String.valueOf(pagNo), nonce};
        Call<ResultDO<List<Assess>>> call = ApiClient.getApiAdapter().getComment(1,id,
                pageSize, pagNo,  nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<List<Assess>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Assess>>> call, Response<ResultDO<List<Assess>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pagNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult().size() == 10) {
                        pagNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.setmData(dataSet);
                    adapter.notifyDataSetChanged();
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Assess>>> call, Throwable t) {
                ptrFrame.refreshComplete();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
